

import java.util.*;
import java.util.concurrent.DelayQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Microsoft
 * Date: 2023-03-09
 * Time: 18:24
 */
public class TestBinaryTree {
    static class TreeNode{
        public char val;//数据
        public TreeNode left;//左孩子的引用
        public TreeNode right;//右孩子的引用

        //构造方法
        public TreeNode(char val) {
            this.val = val;
        }
    }

    //就像我们的头节点一样，我们的树中有根节点
    public TreeNode root;//二叉树的根节点

    public TreeNode createTree(){
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
//        B.left = D;
//        B.right = E;
//        C.left = F;
//        C.right = G;
//        E.right = H;
        this.root = A;
        return root;
    }

    // 前序遍历 根 左子树 右子树 我们用递归实现 非递归也可以
    public void preOrder(TreeNode root){
        if (root == null) {
            return;
        }
        System.out.print(root.val + " ");//根
        preOrder(root.left);//左
        preOrder(root.right);//右
    }

    /**
     * 非递归通过栈，模拟递归实现前序遍历
     * @param root
     */
    public void preOrder1(TreeNode root){
        if (root == null) {
            return;
        }
        Deque<TreeNode> stack = new ArrayDeque<>();
        TreeNode cur = root;

        while (cur != null || !stack.isEmpty()){
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                cur = cur.left;
            }

            TreeNode top = stack.pop();
            cur = top.right;
        }
    }

    // 中序遍历 左子树 根 右子树
    public void inOrder(TreeNode root){
        if (root == null) {
            return;
        }
        inOrder(root.left);//左
        System.out.print(root.val + " ");//根
        inOrder(root.right);//右
    }

    /**
     * 用非递归实现中序遍历
     * @param root
     */
    public void inOrder1(TreeNode root){

    }

    // 后序遍历 左子树 右子树 根
    public void postOrder(TreeNode root){
        if (root == null) {
            return;
        }
        postOrder(root.left);//左
        postOrder(root.right);//右
        System.out.print(root.val + " ");//根
    }

    /**
     * 后序遍历
     * @param root
     * @return
     */
    public void postOrder1(TreeNode root) {
        if (root == null) {
            return;
        }
        Deque<TreeNode> stack = new ArrayDeque<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while (cur != null || !stack.isEmpty()){
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }

            TreeNode top = stack.peek();
            if (top.right == null || top.right == prev /*代表top被打印过*/) {
                System.out.print(top.val + " ");
                stack.pop();
                prev = top;
            }else {
                cur = top.right;
            }
        }
    }

    // 获取树中节点的个数
    public int size(TreeNode root){
        if (root == null) {
            return 0;
        }
        return size(root.left) + size(root.right) + 1;
    }
    // 获取树中节点的个数
    public int nodeSize;
    public void size2(TreeNode root){
        if (root == null) {
            return;
        }
        nodeSize++;
        size2(root.left);
        size2(root.right);
    }
    // 获取叶子节点的个数（子问题）
    int getLeafNodeCount(TreeNode root){
        if (root == null) {//防止root传递为空或者单分支情况下会遇到左子树或者右子树为空的情况
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount(root.left) + getLeafNodeCount(root.right);
    }
    // 获取叶子节点的个数（遍历问题）
    public int leafSize;
    void getLeafNodeCount2(TreeNode root){
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            leafSize ++;
        }
        getLeafNodeCount2(root.left);
        getLeafNodeCount2(root.right);
    }

    // 获取第K层节点的个数
    int getKLevelNodeCount(TreeNode root,int k){
        if (root == null) {
            return 0;
        }
        if (k == 1) {
            return 1;
        }
        int leftSize = getKLevelNodeCount(root.left,k-1);
        int rightSize = getKLevelNodeCount(root.right,k-1);
        return leftSize + rightSize;
    }

    // 检测值为value的元素是否存在
    TreeNode find(TreeNode root, int val){
        if (root == null) {
            return null;
        }
        if (root.val == val) {
            return root;
        }
        TreeNode leftTree = find(root.left,val);
        if (leftTree != null) {
            return leftTree;
        }
        TreeNode rightTree = find(root.right,val);
        if (rightTree != null) {
            return rightTree;
        }
        return null;
    }

    //判断两棵二叉树是否相同
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }

        if (p.val != q.val) {//不能通过相等判断，因为还有左右子树的判断
            return false;
        }
        //走到这里说明值相同，并接着判断对应的左右子树

        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }

    //另一棵树的子树
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null || subRoot == null) {
            return false;
        }
        if (isSameTree(root,subRoot)) {
            return true;
        }
        if (isSubtree(root.left,subRoot)) {
            return true;
        }
        if (isSubtree(root.right,subRoot)) {
            return true;
        }
        return false;
    }

    //翻转二叉树
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    // 获取二叉树的高度
    int getHeight(TreeNode root){
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        return leftHeight > rightHeight ? (leftHeight + 1) : (rightHeight + 1);
    }

    //判断一棵二叉树是否为平衡二叉树
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int leftH = getHeight(root.left);
        int rightH = getHeight(root.right);
        if (Math.abs(leftH - rightH) > 1) {
            return false;
        }
        return isBalanced(root.left) &&
        isBalanced(root.right);
    }

    // 获取二叉树的高度,同时判断是否为平衡二叉树，如果不满足返回-1
    int getHeight2(TreeNode root){
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight2(root.left);
        if (leftHeight < 0) return -1;
        int rightHeight = getHeight2(root.right);
        if (rightHeight < 0) return -1;
        if (Math.abs(leftHeight - rightHeight) <= 1) {
            return Math.max(leftHeight,rightHeight) + 1;
        }else {
            return -1;
        }
    }

    //判断一棵二叉树是否为平衡二叉树
    public boolean isBalanced2(TreeNode root) {
        return getHeight2(root) >= 0;
    }

    //层序遍历：从上到下，从左至右
    void levelOrder(TreeNode root){
        if (root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val + " ");
            if (cur.left != null) {
                queue.offer(cur.left);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }

    public List<List<Integer>> levelOrder1(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();//每次进入都要判断队列当中有几个元素，因为这几个是一层的元素
            List<Integer> tmp = new ArrayList<>();
            while (size != 0) {
                TreeNode cur = queue.poll();

//                tmp.add(cur.val);
                size--;
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            list.add(tmp);//将整个一层放入到大的List里面
        }
        return list;
    }

    /**
     * 找到从根节点到指定节点node路径上的所有的节点，存放到栈当中
     * @param root
     * @param node
     * @param stack
     * @return
     */
    public boolean getPath(TreeNode root, TreeNode node, Deque<TreeNode> stack){
        if (root == null || node == null) {
            return false;
        }
        stack.push(root);
        //放完之后要进行检查
        if (root == node) {
            return true;
        }

        boolean ret1 = getPath(root.left,node,stack);
        if (ret1 == true) {
            return true;
        }
        boolean ret2 = getPath(root.right,node,stack);
        if (ret2 == true) {
            return true;
        }
        stack.pop();
        return false;
    }

    //寻找两个节点的最近祖宗节点
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        //1.两个栈当中 存储好数据
        Deque<TreeNode> stack1 = new LinkedList<>();
        getPath(root,p,stack1);
        Deque<TreeNode> stack2 = new LinkedList<>();
        getPath(root,q,stack2);

        //2.判断栈的大小
        int size1 = stack1.size();
        int size2 = stack2.size();
        if (size1 > size2) {
            int size = size1 - size2;
            while (size != 0) {
                stack1.pop();
                size--;
            }
        }else {
            int size = size2 - size1;
            while (size != 0) {
                stack2.pop();
                size--;
            }
        }

        //栈里面数据的个数是一样的
        while (!stack1.isEmpty() && !stack2.isEmpty()) {
            if (stack1.peek() != stack2.peek()) {
                stack1.pop();
                stack2.pop();
            }else {
                return stack1.peek();
            }
        }
        return null;
    }


    //---------------------------------------------------------------------------
    public static int i = 0;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder,0,inorder.length - 1);
    }
    public TreeNode buildTreeChild(int[] preorder, int[] inorder,int inbegin,int inend) {
        if (inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode((char)preorder[i]);

        //找到当前根，在中序遍历的位置
        int rootIndex = findIndex(inorder,inbegin,inend,preorder[i]);
        i++;
        root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex - 1);
        root.right = buildTreeChild(preorder,inorder,rootIndex + 1,inend);
        return root;
    }

    private int findIndex(int[] inorder,int inbegin,int inend,int key) {
        for(int i = inbegin;i <= inend;i++){
            if(inorder[i] == key){
                return i;
            }
        }
        return -1;
    }


    // 判断一棵树是不是完全二叉树
    boolean isCompleteTree(TreeNode root){
        if(root == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            TreeNode cur = queue.poll();
            if (cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else{
                break;
            }
        }

        while (!queue.isEmpty()) {
            TreeNode tmp = queue.poll();
            if (tmp != null) {
                return false;
            }
        }
        return true;
    }
}







































